import { login, logout, getUserInfo } from '@/api/login'
import { getOrganReferencedDictionary } from '@/api/dictionary'
import { queryTenantList, querySubordinateOrgan } from '@/api/organ'
import { getOrganList, setOrganList, getToken, setToken, removeToken, 
getTenantId, setTenantId, setOrganId, getOrganId, setLoginUser, getLoginUser, 
setOrganPath, setDictionary, getDictionary, setTenantList, getTenantList, 
filterSystemErrorCode, createOrganOption } from '@/utils/auth'
import localStorageUtil from '@/utils/localStorageUtil'
import sessionStorageUtil from '@/utils/sessionStorageUtil'

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    },
    permission:{
      routes:[]
    },
    authorities: localStorageUtil.fetch('BUILD-ROUTES')
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_AUTHORITIES: (state, userAuthorities) => {
      state.permission.routes = userAuthorities
    }
  },

  actions: {
    // 用户名登录
    Login({ commit, dispatch }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          const data = response.data
          debugger
          console.log(response)
          console.log(response.data)
          setToken('bearer ' + data.token)

          commit('SET_TOKEN', 'bearer ' + data.token)
          commit('SET_NAME', data.userName)
          setLoginUser(data.id)
          setTenantId(data.tenantId)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          // commit('SET_ROLES', response.data.roles)
          commit('SET_ROLES', data.roles)
          setOrganId(data.organId)
          setOrganPath(data.organPath)
          sessionStorageUtil.saveObject('SET_ROLES', data.roles)
          localStorageUtil.save('authorities', data.userAuthorities)
          setTimeout(() => {
            dispatch('GetDictionary', { organId: data.organId, sys: 1, organPath: data.organPath, tenantId:data.tenantId })
          }, 1000)
          setTimeout(() => {
            dispatch('GetOrganTree', { organId: data.organId, sys: 1, organPath: data.organPath, tenantId:data.tenantId })
          }, 1200)
          setTimeout(() => {
            dispatch('GetTenantList', { organPath: data.organPath, sys: 1, organPath: data.organPath, tenantId:data.tenantId })
          }, 1500)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    GetDictionary({ commit }, params) {
      return new Promise((resolve, reject) => {
        getOrganReferencedDictionary(params).then(response => {
          setDictionary(response.data.data)
          filterSystemErrorCode(response.data.data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    GetOrganTree({ commit }, params) {
      return new Promise((resolve, reject) => {
        querySubordinateOrgan(params).then(response => {
          setOrganList(response.data.data)
          createOrganOption()
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    GetTenantList({ commit }, params) {
      return new Promise((resolve, reject) => {
        queryTenantList(params).then(response => {
          setTenantList(response.data.data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        const userId = getLoginUser()
        const organId = getOrganId()
        getUserInfo(userId, organId).then(response => {
          // 由于mockjs 不支持自定义状态码只能这样hack
          if (!response.data) {
            reject('Verification failed, please login again.')
          }
          const data = response.data

          localStorageUtil.save('authorities', data.userAuthorities)
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)
            console.log('登录用户：' + userId + '角色:')
            console.log(data.roles)
            debugger

            sessionStorageUtil.saveObject('SET_ROLES', data.roles)
          } else {
            reject('getInfo: roles must be a non-null array!')
          }

          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    //登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        sessionStorageUtil.delete('SET_ROLES')
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        localStorageUtil.save('SET_ROLES', [])
        
        sessionStorageUtil.delete('BUILD-ROUTES')
        sessionStorageUtil.delete('HAS-Generate-Routes');
        sessionStorageUtil.delete('HAS-Generate-Routes');
        removeToken()
        resolve()
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({ commit, dispatch }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          dispatch('GenerateRoutes', data) // 动态修改权限后 重绘侧边菜单
          resolve()
        })
      })
    }
  }
}

export default user
